package net.xdclass.forum.controller;

import net.xdclass.forum.domain.User;
import net.xdclass.forum.service.UserService;
import net.xdclass.forum.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet(name = "userServlet", urlPatterns = {"/user"})
public class UserServlet extends BaseServlet {
    private UserService userService = new UserServiceImpl();

    /**
     * 注册接口
     *
     * @param req
     * @param resq
     * @throws Exception
     */
    public void register(HttpServletRequest req, HttpServletResponse resq) throws Exception {
        User user = new User();
        Map<String, String[]> map = req.getParameterMap();
        try {
            BeanUtils.populate(user, map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        int i = userService.register(user);

        if (i > 0) {
            //注册成功，跳转到登录界面
            req.getRequestDispatcher("/user/login.jsp").forward(req,resq);
        } else {
            //注册失败，跳转到注册页面
            req.getRequestDispatcher("/user/register.jsp").forward(req,resq);
        }
    }

    /**
     * 用户登录接口
     * @param req
     * @param resp
     */
    public void login(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String phone = req.getParameter("phone");
        String pwd = req.getParameter("pwd");
        User user = userService.login(phone, pwd);
        if (user != null){
            req.getSession().setAttribute("loginUser",user);
            // 页面跳转
            resp.sendRedirect("/topic?method=list&c_id=1");
        } else {
            req.setAttribute("msg","用户名或密码错误");
            req.getRequestDispatcher("/user/login.jsp").forward(req,resp);
        }
    }

    /**
     * 退出登录接口
     * @param req
     * @param resp
     */
    public void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.getSession().invalidate();
        // 页面跳转
        resp.sendRedirect("/topic?method=list&c_id=1");
    }

}
